package com.reins.bookstore.daoimpl;

import com.reins.bookstore.dao.OrderDao;
import com.reins.bookstore.entity.OrderItem;
import com.reins.bookstore.repository.OrderRepository;
import com.reins.bookstore.repository.OrderlistRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.reins.bookstore.entity.Orders;

import java.util.Date;
import java.util.List;

@Repository
public class OrderDaoImpl implements OrderDao {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderlistRepository orderlistRepository;

    @Override
    public Orders findById(Integer id){
        return orderRepository.findById(id).get();
    }
    @Override
    public List<Orders> findAll(){
        return orderRepository.findAll();
    }
    @Override
    public List<Orders> findAll(Date frontDate, Date backDate){
        return orderRepository.findAllByDate(frontDate,backDate);
    }


    @Override
    public List<Orders> findAllOrdersByUserId(Integer id){
        return orderRepository.findAllOrdersByUserId(id);
    }

    @Override
    public List<Orders> findAllOrdersByUserId(Integer id, Date frontDate, Date backDate){
//        frontDate.setHours(0);
//        frontDate.setMinutes(0);
//        frontDate.setSeconds(0);
//        backDate.setHours(23);
//        backDate.setMinutes(59);
//        backDate.setSeconds(59);

        return orderRepository.findAllOrdersByUserId(id,frontDate,backDate);
    }

    @Override
    public Orders save(Orders add)
    {
        return orderRepository.save(add);
    }
    @Override
    public void deleteOrderById(Integer id){
        deleteOrderItemsByOrderId(id);  // 一并删除OrderItem列表中的条目，先删除这个因为外键的方向性
        orderRepository.deleteById(id); // 删除Order列表中的条目
    }
    @Override
    public void deleteOrderItemsByOrderId(Integer orderId) {
        List<OrderItem> findAll = findAllOrderlistsByOrderId(orderId);
        for (OrderItem oneline : findAll) {
            orderlistRepository.deleteById(oneline.getOrderlistId());
        }
    }
    @Override
    public Orders saveAndFlush(Orders add){
        return orderRepository.saveAndFlush(add);
    }
    @Override
    public List<OrderItem> findAllOrderlistsByOrderId(Integer id){
        return orderlistRepository.findAllOrderlistsByOrderId(id);
    }
    @Override
    public void savelist(OrderItem add){
        orderlistRepository.save(add);
    }

    @Override
    public List<Orders> filterByDate(Date frontDate, Date backDate){
        return orderRepository.filterByDate(frontDate,backDate);
    }


}

